﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace wpf.Triage.Behavior
{
    class DragInCanvasBehavior: Behavior<UIElement>
    {
        /// <summary>
        /// 画布
        /// </summary>
        private Canvas canvas;
        private bool isDragging;
        private Point mouseOffset;
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
            this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
        }

        /// <summary>
        /// Behavior.OnDetaching()，移出事件处理程序
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
            this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
        }
        private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (canvas == null)
            {
                canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;
            }
            if (canvas != null)
            {
                isDragging = true;
                mouseOffset = e.GetPosition(this.AssociatedObject);
                AssociatedObject.CaptureMouse();
            }
        }

        private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (canvas != null && isDragging == true)
            {
                Point p = e.GetPosition(canvas);
                AssociatedObject.SetValue(Canvas.TopProperty, p.Y - mouseOffset.Y);
                AssociatedObject.SetValue(Canvas.LeftProperty, p.X - mouseOffset.X);
            }
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (isDragging)
            {
                AssociatedObject.ReleaseMouseCapture();
                isDragging = false;
            }
        }
    }
}
